<script lang="ts" setup>
import { Banner, ProcessNode, CertificateContent, Footer } from "#/components/certificate-home"
import { getCertificationApi } from "#/api/lesson/tenant"
import { getCertificateFirstPageForClientApi } from "#/api/certificate/list"
import { isValidJSON } from '#/utils/isValidJSON'
import { ref, onMounted, watch, nextTick } from "vue"
import { cloneDeep } from '@vben/utils'
import { useRoute, useRouter } from 'vue-router';
import { useAccessStore } from '@vben/stores';
import PDF from '#/components/pdf.vue';
import { getMyselfCertifiedApi } from "#/api/certificate/list"
import { getCheckWhiteApi } from '#/api/certificate/white-link';
import { getExamIdByUserCertificationApi } from '#/api/manage/examination-mgr';
import DialogPay from "./modules/pay/dialog-pay.vue"

defineOptions({ name: 'Home' });

const route = useRoute();
const router = useRouter();
const accessStore = useAccessStore();
const dialogVisible = ref(false)
const isQuick = ref(false);
const obs = ref({ Key: '' })
console.log(route.params.id);
const certificationId = ref(route.params.id);
const examId = ref('');
const loading = ref(false)
const footerHeight = ref(0)
const defaultWorkSpace = ref<any>({
  banner: {
    bannerUrl: '',
    textConfigs: []
  },
  processNode: {
    processNodeConfigs: []
  },
  certificateContent: {
    certificateContentConfigs: []
  },
  footer: {
    showFooter: false,
    provideContent: '',
    phone: '',
    email: '',
    publicAccount: {
      code: '',
      desc: ''
    },
    service: {
      code: '',
      desc: ''
    }
  },
  activeName: 'banner'
})
const payDialog=ref(false)
const workSpace = ref(cloneDeep(defaultWorkSpace.value))
const loaded = ref(false)

const getExamId = () => {
  getExamIdByUserCertificationApi(certificationId.value as string).then(res => {
    examId.value = res;
  })
}
const toIntro = (type: string) => {
  if (type == 'joinExam' && examId.value) {
    router.push({
      path: `/accreditExam/explainCore/${examId.value}`
    });
  } else if (type === 'startLearn') {
    // realNameDialog.value = true
    router.push({
      path: '/lesson/intro',
      query: {
        certifiedId: certificationId.value
      }
    });
  } else if (type == 'myCert') {
    dialogVisible.value = true
    getMyselfCertifiedApi({ certificationId: certificationId.value }).then(res => {
      obs.value.Key = res;
    })
  }else if(type == 'buyCert'){
    // 支付
    payDialog.value=true
  }
};

const setDisabled = (data: any) => {
  const { buttonFunc, buttonType } = data
  if (buttonFunc ==="buyCert" && accessStore.accessToken)return false
  if (buttonType === 'link') return false;
  if (buttonFunc === 'startLearn') return false;
  if (buttonFunc === 'joinExam' && accessStore.accessToken && isQuick.value && examId.value) return false;
  if (buttonFunc === 'myCert' && accessStore.accessToken && isQuick.value) return false;
  return true;
};

const getCertificateFirstPage = () => {
  loading.value = true
  getCertificateFirstPageForClientApi({
    certificateId: certificationId.value,
    status: 1
  }).then((res: any) => {
    const { configTemplate } = res
    // 解析 configTemplate 并保持 workSpace 的完整结构
    try {
      const parsedConfig = isValidJSON(configTemplate) ? JSON.parse(configTemplate) as any[] : []
      const config = parsedConfig?.[0] || {}
      // 使用 Object.assign 来合并数据，保持默认结构
      workSpace.value = {
        ...cloneDeep(defaultWorkSpace.value),
        ...config
      }
    } catch (error) {
      console.error('解析 configTemplate 失败:', error)
      // 如果解析失败，保持默认结构
    }
  }).finally(() => {
    console.log('getCertificateFirstPage')
    console.log(workSpace.value)
    loaded.value = true
    loading.value = false
  })
}
const getCertList = () => {
    loading.value = true
    getCertificationApi({}).then(res => {
      const { data } = res
      console.log(data)
      if (data.length > 0) {
        certificationId.value = data[0].id
        getCertificateFirstPage()
        getCert()
      }
    }).finally(() => {
      loading.value = false
    })
}
const getCert = () => {
  if (accessStore.accessToken) {
    // 目前定义为certifiedId
    const params = {
      certifiedId: certificationId.value
    }
    getCheckWhiteApi(params as any).then((res) => {
      isQuick.value = res.checked;
    });
    getExamId();
  }
}

onMounted(() => {
  console.log('certificationId.value')
  console.log(certificationId.value)
  if (certificationId.value) {
    getCertificateFirstPage()
    getCert()
  } else {
    getCertList()
  }
})
</script>
<template>
  <section ref="previewRef" v-loading="loading" class="flex-1 overflow-hidden relative" style="padding: 0px;">
    <div v-show="loaded" class="w-full h-full overflow-y-scroll">
      <div class="w-full h-auto mb-[16px]">
        <Banner v-show="workSpace.banner.bannerUrl" v-model:banner="workSpace.banner" :edit="false" />
      </div>
      <div class="w-full max-w-[1248px] m-auto pl-[24px] pr-[24px] mb-[16px]">
        <ProcessNode v-show="workSpace.processNode.processNodeConfigs.length"
          v-model:processNode="workSpace.processNode" />
      </div>
      <div class="w-full max-w-[1248px] m-auto pl-[24px] pr-[24px] mb-[16px]">
        <CertificateContent v-show="workSpace.certificateContent.certificateContentConfigs.length"
          v-model:certificateContent="workSpace.certificateContent" :setDisabled="setDisabled" :toIntro="toIntro" />
      </div>
      <div v-show="loaded && workSpace.footer.showFooter" id="footerWrapper" class="w-full">
        <Footer v-show="workSpace.footer.showFooter" v-model:footer="workSpace.footer" />
      </div>
    </div>
    <!-- 查看证书 -->
    <el-dialog v-model="dialogVisible" :destroy-on-close="true" title="我的证书" width="600px" :append-to-body="true"
      :close-on-click-modal="false" :before-close="() => dialogVisible = false">
      <div class="overflow-auto h-[500px]">
        <PDF :obs="obs"></PDF>
      </div>
    </el-dialog>
    <DialogPay :visible="payDialog" @update:visible="payDialog = $event"></DialogPay>
  </section>
</template>

<style scoped></style>
